package cn.cque.filter;

import cn.cque.entity.InfoResult;
import cn.cque.entity.User;
import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: XWC
 * @ClassName: LoginInterceptor
 * @Date: 2020/10/5
 * @Time: 15:24
 * @Description:
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取uri（去除localhost:8888）
        String uri = request.getRequestURI();
        // 是否是AJAX请求的标志位
        boolean isAjax = false;
        String ajaxHeader = request.getHeader("X-Requested-With");
        if ((!StringUtils.isEmpty(ajaxHeader)) && ajaxHeader.equalsIgnoreCase("XMLHttpRequest")) {
            isAjax = true;
        }
        //拦截所有购物车和订单的请求
        if (uri.indexOf("/admin")<0&&(uri.indexOf("/cart") >= 0 || uri.indexOf("/order") >= 0)) {
            User loginUser = (User) request.getSession().getAttribute("loginUser");
            //如果没登录
            if (loginUser == null) {
                if (isAjax) {
                    Gson gson=new Gson();
                    response.setContentType("application/json;charset=utf-8");
                    String json = gson.toJson(InfoResult.ERROR("用户未登录"));
                    response.getWriter().write(json);
                    return false;
                }else {
                    //重定向到登录界面
                    response.sendRedirect(request.getContextPath() + "/jsp/login.jsp");
                    return false;
                }
            }
        }
        //放行
        return true;
    }
}